﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using CardScreening.Properties;
using Tools.InfoStorage;
using Tools.Net;
using Tools;

namespace CardSecretScreening
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private readonly IniRw _inifiles = new IniRw(Directory.GetCurrentDirectory() + "/main.cfg");
        private int _count;
        private int _len;

        private readonly Dictionary<string, double> _array = new Dictionary<string, double>();
        private readonly Dictionary<string, double> _array2 = new Dictionary<string, double>();
        private readonly List<string> _arrayList = new List<string>();

        private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
        {
            progressBar2.Maximum = _array2.Count;
            progressBar2.Value = 0;
            int cf = 0;
            int sb = 0;
            foreach (var item in _array2)
            {
                string cardNum = item.Key;
                int amount = Convert.ToInt32(item.Value.ToString("F0"));

                //if (cardNum.Length < _len) { continue; }
                //cardNum = cardNum.Substring(cardNum.Length - _len, _len);
                progressBar2.Value++;
                label6.Text = String.Format("%{0}", ((Convert.ToDouble(progressBar2.Value) / progressBar2.Maximum) * 100).ToString("F2"));
                try
                {
                    string url = String.Format("http://192.168.1.123:8080/Views/Apis/CardImport$a8681daf3386d305.aspx?type={0}&data={1}", comboBox2.SelectedItem.ToString().Equals("电信") ? "charge" : "charge_cards", cardNum);
                    var text = Http.ReadPage(url);
                    if (text.Equals("1|0")) { sb++; UpdateAdd(amount, true); }
                    else { cf++; UpdateAdd(amount, false); }

                }
                catch { cf++; UpdateAdd(amount, false); }

                label7.Text = String.Format("导入：{0}张，失败：{1}张", sb, cf);
            }
            label7.Text = String.Format("导入完毕，成功：{0}张，失败：{1}张", sb, cf);
        }

        private void Form1Load(object sender, EventArgs e)
        {
            string path = Environment.CurrentDirectory + "\\10010.cds";
            PrepaidCard.Query.index = PrepaidCard.Query.LoadCdsFromFile(path);
            if (PrepaidCard.Query.index == -1) { MessageBox.Show("验证码识别库载入失败！"); }

            //MessageBox.Show(PrepaidCard.Query.QStatus10010("981201373847848").statusDesc);
            //MessageBox.Show(PrepaidCard.Query.QStatus10000("4141001204460121886").statusDesc);
            dateTimePicker1.Value = DateTime.Now.AddDays(-1);
            dateTimePicker2.Value = DateTime.Now;
            CheckForIllegalCrossThreadCalls = false;
            dataGridView1.Rows.Add(new object[] { 10, 0, 0, 0, 0 });
            dataGridView1.Rows.Add(new object[] { 20, 0, 0, 0, 0 });
            dataGridView1.Rows.Add(new object[] { 30, 0, 0, 0, 0 });
            dataGridView1.Rows.Add(new object[] { 50, 0, 0, 0, 0 });
            dataGridView1.Rows.Add(new object[] { 100, 0, 0, 0, 0 });
            dataGridView1.Rows.Add(new object[] { 200, 0, 0, 0, 0 });
            dataGridView1.Rows.Add(new object[] { 300, 0, 0, 0, 0 });
            dataGridView1.Rows.Add(new object[] { 500, 0, 0, 0, 0 });
            dataGridView1.Rows.Add(new object[] { 1000, 0, 0, 0, 0 });
            dataGridView1.Rows.Add(new object[] { "合计", 0, 0, 0, 0 });
        }

        private void BackgroundWorker2DoWork(object sender, DoWorkEventArgs e)
        {
            int tn = Int32.Parse(_inifiles.IniReadValue("system", "thread-num"));
            _count = _array.Count;
            progressBar1.Maximum = _count;
            progressBar1.Value = 0;
            listBox1.Items.Clear();
            var array = Often.DigitalPacket(_count, tn);
            foreach (var item in array)
            {
                var td = new Thread(Query);
                td.Start(item);
            }
        }

        void Query(object obj)
        {
            var kvp = (KeyValuePair<int, int>)obj;

            for (var i = kvp.Key; i < kvp.Value; i++)
            {
                var str = _arrayList[i];
                int p = Convert.ToInt32(str.Split(new[] { '|', ' ' })[1]);
                string cardNum = str.Split(new[] { '|', ' ' })[0];
                try
                {
                    if (_len == 15 ? Inquiry10010(cardNum) : Inquiry10000(cardNum))
                    {
                        AddItems(str);
                        lock (toolStripStatusLabel2) toolStripStatusLabel2.Text = String.Format("数量：{0}", listBox1.Items.Count);
                        ListAdd(cardNum, p);
                    }
                }
                catch
                {

                }

                lock (progressBar1) progressBar1.Value++;
                lock (lable2) toolStripStatusLabel2.Text = String.Format("查询：{0}", str);
                lock (label1) label1.Text = String.Format("%{0}", ((Convert.ToDouble(progressBar1.Value) / _count) * 100).ToString("F2"));
                lock (toolStripStatusLabel1) { toolStripStatusLabel1.Text = String.Format("{0}/{1}", progressBar1.Value, progressBar1.Maximum); }
            }
            lock (lable2) lable2.Text = String.Format("线程编号:『{0}-{1}』,运行结束.", kvp.Key, kvp.Value);
        }

        private bool Inquiry10000(string text)
        {
            string cardNum = text.Split(new[] { '|', ' ' })[0];
            if (cardNum.Length < 19) { return false; }
            cardNum = cardNum.Substring(cardNum.Length - 19, 19);
            var status = PrepaidCard.Query.QStatus10000(cardNum);
            if (status == null || status.statusDesc.Equals("")) lock (lable2) lable2.Text = String.Format("电信卡密:{0},查询异常.", cardNum);
            return status.statusDesc.Equals("\\u53EF\\u7528");
        }

        private bool Inquiry10010(string text)
        {
            string cardNum = text.Split(new[] { '|', ' ' })[0];
            if (cardNum.Length < 15) { return false; }
            cardNum = cardNum.Substring(cardNum.Length - 15, 15);
            var status = PrepaidCard.Query.QStatus10010(cardNum);
            if (status == null || status.statusDesc.Equals("")) 
                lock (lable2) lable2.Text = String.Format("联通卡密:{0},查询异常.", cardNum);
            return status.statusDesc.Equals("未充值");
        }

        private void AddItems(object o)
        {
            //if (listBox1.Items.Cast<object>().Any(item => item.ToString().Equals(o.ToString()))) { return; }
            listBox1.Items.Add(o.ToString().Replace('|', '\t'));
            toolStripStatusLabel2.Text = listBox1.Items.Count.ToString();
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedItem == null) return;
            if (!backgroundWorker3.IsBusy)
            {
                backgroundWorker3.RunWorkerAsync();
            }
        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {

        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            _len = comboBox2.SelectedItem.ToString().Equals("电信") ? 19 : 15;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
        {
            string url = String.Format("http://192.168.1.123:8080/Views/Apis/CardsExport$e96a98bb966f6092.aspx?type={0}&beginTime={1}&endTime={2}",
                comboBox2.SelectedItem.ToString().Equals("电信") ? "charge" : "charge_cards",
                dateTimePicker1.Value.ToString("yyyy-MM-dd"),
                dateTimePicker2.Value.ToString("yyyy-MM-dd"));
            label7.Text = Resources.Form1_backgroundWorker3_DoWork_下载数据中__;
            var text = Http.ReadPage(url);
            Text = String.Format("卡密筛选 - {0} - [{1}>{2}]",
                comboBox2.SelectedItem, dateTimePicker1.Value.ToString("yyyy-MM-dd"), dateTimePicker2.Value.ToString("yyyy-MM-dd"));
            var ara = text.Split('\n');
            _count = ara.Length;
            progressBar2.Maximum = _count;
            progressBar2.Value = 0;
            int cf = 0;
            foreach (var item in ara)
            {
                if (item.Split(new[] { '|', ' ', '\t' }).Length < 2) continue;
                string cardNum = item.Split(new[] { '|', ' ', '\t' })[0];
                double amount = Convert.ToDouble(item.Split(new[] { '|', ' ', '\t' })[1]);


                if (cardNum.Length < _len) { continue; }
                cardNum = cardNum.Substring(cardNum.Length - _len, _len);
                progressBar2.Value++;
                label6.Text = String.Format("%{0}", ((Convert.ToDouble(progressBar2.Value) / progressBar2.Maximum) * 100).ToString("F2"));
                try
                {
                    _array.Add(cardNum, amount);
                    _arrayList.Add(String.Format("{0}|{1}", cardNum, amount));
                    //lable2.Text = string.Format("数量:{0}", _array.Count);
                }
                catch { cf++; }
                label7.Text = String.Format("获取：{0}张，重复：{1}张", _array.Count, cf);
            }
            label7.Text = String.Format("获取完毕，正确：{0}张，重复：{1}张", _array.Count, cf);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (_array.Count == 0) return;
            _array2.Clear();
            if (!backgroundWorker2.IsBusy)
            {
                toolStripStatusLabel1.Text = Resources.Form1_Button4Click_;
                backgroundWorker2.RunWorkerAsync();
            }
        }

        private void ListAdd(string str, int p)
        {
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                if (r.Cells[0].Value.ToString().Equals("合计"))
                {
                    r.Cells[1].Value = Convert.ToInt32(r.Cells[1].Value.ToString()) + 1;
                    r.Cells[2].Value = Convert.ToInt32(r.Cells[2].Value.ToString()) + p;
                }
                else
                {
                    int price = Convert.ToInt32(r.Cells[0].Value.ToString());
                    if (price != p) continue;
                    r.Cells[1].Value = Convert.ToInt32(r.Cells[1].Value.ToString()) + 1;
                    r.Cells[2].Value = Convert.ToInt32(r.Cells[2].Value.ToString()) + price;
                }

            }

            _array2.Add(str, p);
        }

        private void UpdateAdd(int p, bool flag)
        {
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                if (r.Cells[0].Value.ToString().Equals("合计"))
                {
                    if (flag) r.Cells[3].Value = Int32.Parse(r.Cells[3].Value.ToString()) + 1;
                    else r.Cells[4].Value = Int32.Parse(r.Cells[4].Value.ToString()) + 1;
                }
                else
                {
                    int price = Convert.ToInt32(r.Cells[0].Value.ToString());
                    if (price != p) continue;
                    if (flag) r.Cells[3].Value = Int32.Parse(r.Cells[3].Value.ToString()) + 1;
                    else r.Cells[4].Value = Int32.Parse(r.Cells[4].Value.ToString()) + 1;
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.ExitThread();
            Application.Exit();
        }

        private void button3_Click(object sender, EventArgs e)
        {


            if (comboBox1.SelectedItem == null || comboBox2.SelectedItem == null)
            {
                MessageBox.Show("请选择面值，运营商");
                return;
            }
            button5.Enabled = false;
            button1.Enabled = false;
            var ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                int cf = 0;
                var ara = File.ReadAllLines(ofd.FileName);
                _count = ara.Length;
                progressBar2.Maximum = _count;
                progressBar2.Value = 0;
                foreach (var item in ara)
                {
                    if (item.Split(new[] { '|', ' ', '\t' }).Length < 2) continue;
                    string cardNum = item.Split(new[] { '|', ' ', '\t' })[0];
                    string cardSecret = item.Split(new[] { '|', ' ', '\t' })[1];
                    double amount = Convert.ToDouble(comboBox1.SelectedItem);


                    if (cardNum.Length < _len) { continue; }
                    cardNum = cardNum.Substring(cardNum.Length - _len, _len);
                    progressBar2.Value++;
                    label6.Text = String.Format("%{0}", ((Convert.ToDouble(progressBar2.Value) / progressBar2.Maximum) * 100).ToString("F2"));
                    try
                    {
                        _array.Add(cardNum + "|" + cardSecret, amount);
                        _arrayList.Add(String.Format("{0}|{1}", cardNum + "|" + cardSecret, amount));
                        //lable2.Text = string.Format("数量:{0}", _array.Count);
                    }
                    catch { cf++; }
                    label7.Text = String.Format("获取：{0}张，重复：{1}张", _array.Count, cf);
                }
                label7.Text = String.Format("获取完毕，正确：{0}张，重复：{1}张", _array.Count, cf);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var sfd = new SaveFileDialog { DefaultExt = ".txt" };
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string t = "";
                foreach (var item in listBox1.Items)
                {
                    t += item + "\n";
                }

                File.WriteAllText(sfd.FileName, t, Encoding.Default);
                MessageBox.Show(Resources.Form1_button2_Click_导出完毕);
            }
        }

        private void backgroundWorker4_DoWork(object sender, DoWorkEventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem == null || comboBox2.SelectedItem == null)
            {
                MessageBox.Show("请选择面值，运营商");
                return;
            }
            button5.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;
            button4.Enabled = false;
            var ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                _array2.Clear();
                int cf = 0;
                var ara = File.ReadAllLines(ofd.FileName);
                _count = ara.Length;
                progressBar2.Maximum = _count;
                progressBar2.Value = 0;
                foreach (var item in ara)
                {
                    if (item.Split(new[] { '|', ' ', '\t' }).Length < 2) continue;
                    string cardNum = item.Split(new[] { '|', ' ', '\t' })[0];
                    string cardSecret = item.Split(new[] { '|', ' ', '\t' })[1];
                    double amount = Convert.ToDouble(comboBox1.SelectedItem);

                    progressBar2.Value++;
                    label6.Text = String.Format("%{0}", ((Convert.ToDouble(progressBar2.Value) / progressBar2.Maximum) * 100).ToString("F2"));
                    try
                    {
                        _array2.Add(cardNum, amount);
                    }
                    catch { cf++; }
                    label7.Text = String.Format("载入：{0}张，重复：{1}张", _array.Count, cf);
                }
                label7.Text = String.Format("载入完毕，正确：{0}张，重复：{1}张", _array2.Count, cf);
            }
        }
    }
}
